<template>
    <div>
      <template v-if="$route.path === '/exam'">
        <!-- 筛选区 -->
        <el-form :inline="true" :model="filters" class="filter-form" @submit.prevent>
          <el-form-item label="考试时间" class="filter-item">
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="width: 260px;"
            />
          </el-form-item>
          <el-form-item label="考试名称" class="filter-item">
            <el-input v-model="filters.examName" placeholder="请输入考试名称" clearable style="width: 180px;" />
          </el-form-item>
          <el-form-item label="状态" class="filter-item">
            <el-select v-model="filters.status" placeholder="全部" clearable style="width: 140px;">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchList">查询</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="openDialog()">+ 新建考试</el-button>
          </el-form-item>
        </el-form>
  
        <!-- 表格区 -->
        <el-table
          :data="examList"
          border
          style="width: 100%; margin-top: 20px"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column prop="examName" label="考试名称" min-width="120" />
          <el-table-column prop="examDate" label="考试日期" min-width="110">
            <template #default="scope">
              <span>{{ scope.row.examDate ? scope.row.examDate.slice(0, 10) : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="考试时间"
            min-width="160"
            :formatter="row => formatExamTime(row.startTime, row.endTime)"
          />
          <el-table-column prop="classroomCode" label="考场" min-width="80" />
          <el-table-column prop="studentCount" label="考生人数" min-width="80" />
          <el-table-column label="监考老师" min-width="120">
            <template #default="{ row }">
              <span>
                {{ row.proctorTasks && row.proctorTasks.length
                  ? row.proctorTasks.map(t => t.teacherName).join('，')
                  : '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" min-width="100">
            <template #default="{ row }">
              <el-tag :type="statusTagType(row.status)">
                {{ statusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="200">
            <template #default="{ row }">
              <div class="action-btns-group">
                <div class="action-btns-row">
                  <el-button size="small" @click="openDialog(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handleDelete(row.examId)">删除</el-button>
                </div>
                <div class="action-btns-row">
                  <el-button size="small" type="primary" @click="openProctorDialog(row)">分配监考老师</el-button>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 新建/编辑弹窗 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
          <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
            <el-form-item label="考试名称" prop="examName">
              <el-input v-model="form.examName" />
            </el-form-item>
            <el-form-item label="考试规则" prop="ruleId">
              <el-select v-model="form.ruleId" placeholder="请选择考试规则" @change="onRuleChange">
                <el-option v-for="item in ruleOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="考试类型" prop="examType" required>
              <el-select v-model="form.examType" placeholder="请选择考试类型">
                <el-option v-for="item in examTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="课程" prop="courseId">
              <el-select v-model="form.courseId" placeholder="请选择课程">
                <el-option v-for="item in courseOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="考试日期" prop="examDate">
              <el-date-picker v-model="form.examDate" type="date" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-time-picker v-model="form.startTime" value-format="HH:mm:ss" />
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-time-picker v-model="form.endTime" value-format="HH:mm:ss" />
            </el-form-item>
            <el-form-item label="考场" prop="classroomId">
              <el-select v-model="form.classroomId" placeholder="请选择考场">
                <el-option v-for="room in classroomList" :key="room.classroomId" :label="room.classroomCode" :value="room.classroomId" />
              </el-select>
            </el-form-item>
            <el-form-item label="考生人数" prop="studentCount">
              <el-input-number v-model="form.studentCount" :min="1" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="考试说明" prop="description">
              <el-input v-model="form.description" type="textarea" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </template>
        </el-dialog>
  
        <!-- 分配监考老师弹窗 -->
        <el-dialog title="分配监考老师" v-model="proctorDialogVisible" width="600px">
          <div class="exam-info">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="考试名称">{{ currentExam.examName }}</el-descriptions-item>
              <el-descriptions-item label="考试日期">{{ currentExam.examDate ? currentExam.examDate.slice(0, 10) : '-' }}</el-descriptions-item>
              <el-descriptions-item label="考试时间">{{ formatExamTime(currentExam.startTime, currentExam.endTime) }}</el-descriptions-item>
              <el-descriptions-item label="考场">{{ currentExam.classroomCode }}</el-descriptions-item>
              <el-descriptions-item label="考生人数">{{ currentExam.studentCount }}</el-descriptions-item>
              <el-descriptions-item label="当前监考老师">
                {{ currentExam.proctorTasks && currentExam.proctorTasks.length
                  ? currentExam.proctorTasks.map(t => t.teacherName).join('，')
                  : '暂无' }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <el-form :model="proctorForm" ref="proctorFormRef" label-width="100px" style="margin-top: 20px;">
            <el-form-item label="监考老师" prop="teacherIds">
              <el-select 
                v-model="proctorForm.teacherIds" 
                multiple 
                filterable 
                placeholder="请选择监考老师" 
                :loading="teacherLoading" 
                style="width: 100%"
              >
                <el-option 
                  v-for="teacher in teacherList" 
                  :key="teacher.teacherId" 
                  :label="teacher.teacherName" 
                  :value="teacher.teacherId" 
                />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="proctorDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitProctorForm">保存</el-button>
          </template>
        </el-dialog>
      </template>
      <router-view />
    </div>
  </template>
  
  <script setup lang="ts" name="ExamManagement">
  import { ref, reactive, onMounted, onUnmounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import axios from 'axios'
  import ProctorTask from './ProctorTask.vue'
  
  const examTypeOptions = [
    { value: 'MIDTERM', label: '期中考试' },
    { value: 'FINAL', label: '期末考试' },
    { value: 'MAKEUP', label: '补考' },
    { value: 'LEVEL', label: '等级考试' },
    { value: 'COMPETITION', label: '竞赛考试' },
    { value: 'SIMULATION', label: '模拟考试' }
  ]
  const statusOptions = [
    { value: 'PENDING_CONFIRM', label: '待确认' },
    { value: 'ARRANGED', label: '已安排' },
    { value: 'IN_PROGRESS', label: '进行中' },
    { value: 'COMPLETED', label: '已完成' },
    { value: 'CANCELLED', label: '已取消' }
  ]
  
  const filters = reactive({
    dateRange: [],
    examName: '',
    status: ''
  })
  
  const examList = ref([])
  const selectedRows = ref([])
  
  // 监考老师下拉数据
  const teacherList = ref([])
  const teacherLoading = ref(false)
  
  // 教室列表
  const classroomList = ref([])
  
  const courseOptions = ref([])
  
  const ruleOptions = ref([])
  
  const ruleTypeMap = {
    'REGULAR': '普通考试',
    'MAKEUP': '补考',
    'LEVEL': '等级考试',
    'COMPETITION': '竞赛考试'
  }
  
  const fetchClassroomList = async () => {
    try {
      const { data } = await axios.get('/api/classroom/listAll')
      console.log(data)
      classroomList.value = data.data || []
    } catch (e) {
      ElMessage.error('获取教室列表失败')
    }
  }
  
  // 获取教师列表
  const fetchTeacherList = async () => {
    teacherLoading.value = true
    try {
      const { data } = await axios.get('/api/teacher/list')
      teacherList.value = data.data || []
    } catch (e) {
      ElMessage.error('获取教师列表失败')
    } finally {
      teacherLoading.value = false
    }
  }
  
  // 获取考试安排列表
  const fetchList = async () => {
    console.log('fetchList called')
    let params = {}
    if (filters.dateRange.length === 2) {
      params.startDate = filters.dateRange[0]
      params.endDate = filters.dateRange[1]
    }
    if (filters.examName) params.examName = filters.examName
    if (filters.status) params.status = filters.status
  
    try {
      const { data } = await axios.get('/api/exam/arrange/listAll', { params })
      examList.value = data.data || []
      console.log('examList', examList.value)
    } catch (e) {
      ElMessage.error('获取考试安排失败')
    }
  }
  
  const resetFilters = () => {
    filters.dateRange = []
    filters.examName = ''
    filters.status = ''
    // 不自动调用fetchList，需用户点击查询
  }
  
  const handleSelectionChange = (rows) => {
    selectedRows.value = rows
  }
  
  // 新建/编辑考试弹窗
  const dialogVisible = ref(false)
  const dialogTitle = ref('新建考试')
  const formRef = ref()
  const form = reactive({
    examId: null,
    examName: '',
    courseId: null,
    ruleId: null,
    examType: '',
    ruleType: '',
    examDate: '',
    startTime: '',
    endTime: '',
    classroomId: '',
    studentCount: 1,
    status: 'PENDING_CONFIRM',
    description: ''
  })
  
  const formRules = {
    examName: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
    courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
    ruleId: [{ required: true, message: '请选择考试规则', trigger: 'change' }],
    examType: [{ required: true, message: '请选择考试类型', trigger: 'change' }],
    examDate: [{ required: true, message: '请选择考试日期', trigger: 'change' }],
    startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
    studentCount: [{ required: true, type: 'number', message: '请输入考生人数', trigger: 'blur' }]
  }
  
  const openDialog = (row = null) => {
    if (row) {
      dialogTitle.value = '编辑考试'
      Object.assign(form, row)
    } else {
      dialogTitle.value = '新建考试'
      Object.assign(form, {
        examId: null,
        examName: '',
        courseId: null,
        ruleId: null,
        examType: '',
        ruleType: '',
        examDate: '',
        startTime: '',
        endTime: '',
        classroomId: '',
        studentCount: 1,
        status: 'PENDING_CONFIRM',
        description: ''
      })
    }
    dialogVisible.value = true
  }
  
  const submitForm = () => {
    formRef.value.validate(async (valid) => {
      if (!valid) return
      try {
        const submitData = { ...form }
        delete submitData.createTime
        delete submitData.updateTime
        // 拼接日期和时间，使用T分隔
        submitData.startTime = form.examDate && form.startTime ? `${form.examDate}T${form.startTime}` : ''
        submitData.endTime = form.examDate && form.endTime ? `${form.examDate}T${form.endTime}` : ''
        if (form.examId) {
          await axios.put('/api/exam/arrange', submitData)
          ElMessage.success('编辑成功')
        } else {
          await axios.post('/api/exam/arrange', submitData)
          ElMessage.success('创建成功')
        }
        await fetchList()
        dialogVisible.value = false
      } catch (e) {
        ElMessage.error(e?.response?.data?.message || '操作失败')
      }
    })
  }
  
  // 分配监考老师弹窗
  const proctorDialogVisible = ref(false)
  const proctorFormRef = ref()
  const currentExam = ref({})
  const proctorForm = reactive({
    examId: null,
    teacherIds: []
  })
  
  const openProctorDialog = (row) => {
    currentExam.value = { ...row }
    proctorForm.examId = row.examId
    proctorForm.teacherIds = row.proctorTasks ? row.proctorTasks.map(t => t.teacherId) : []
    proctorDialogVisible.value = true
    fetchTeacherList()
  }
  
  const submitProctorForm = async () => {
    try {
      const submitData = {
        examId: proctorForm.examId,
        teacherIds: proctorForm.teacherIds
      }
      await axios.post('/api/exam/arrange/assignProctors', submitData)
      ElMessage.success('监考老师分配成功')
      await fetchList()
      proctorDialogVisible.value = false
    } catch (e) {
      ElMessage.error(e?.response?.data?.message || '分配失败')
    }
  }
  
  const handleDelete = (id) => {
    ElMessageBox.confirm('确定要删除该考试安排吗？', '提示', { type: 'warning' })
      .then(async () => {
        try {
          await axios.delete(`/api/exam/arrange/${id}`)
          ElMessage.success('删除成功')
          fetchList()
        } catch (e) {
          ElMessage.error(e?.response?.data?.message || '删除失败')
        }
      })
      .catch(() => {})
  }
  
  const formatExamTime = (start, end) => {
    return start && end ? `${start} ~ ${end}` : ''
  }
  
  const statusLabel = (status) => {
    const found = statusOptions.find(item => item.value === status)
    return found ? found.label : status
  }
  const statusTagType = (status) => {
    switch (status) {
      case 'ARRANGED': return 'success'
      case 'IN_PROGRESS': return 'warning'
      case 'COMPLETED': return 'info'
      case 'CANCELLED': return 'danger'
      case 'PENDING_CONFIRM': return 'warning'
      default: return ''
    }
  }
  
  function onRuleChange(ruleId) {
    const rule = ruleOptions.value.find(r => r.value === ruleId)
    form.ruleType = rule ? rule.label : ''
  }
  
  const handleVisibilityChange = async () => {
    if (document.visibilityState === 'visible') {
      // 先让后端同步所有考试状态
      await axios.put('/api/proctor/task/syncAllExamStatus')
      // 再刷新考试安排列表
      fetchList()
    }
  }
  
  let autoRefreshTimer = null
  onMounted(() => {
    fetchList()
    fetchTeacherList()
    fetchClassroomList()
    axios.get('/api/course/listAll').then(res => {
      courseOptions.value = (res.data.data || []).map(c => ({ label: c.courseName, value: c.courseId }))
    })
    axios.get('/api/examRules/listAll').then(res => {
      ruleOptions.value = (res.data.data || []).map(r => ({ label: ruleTypeMap[r.ruleType] || r.ruleType, value: r.ruleId, ruleType: r.ruleType }))
    })
    // 自动刷新定时器
    autoRefreshTimer = setInterval(() => {
      fetchList()
    }, 30000) // 30秒刷新一次
    document.addEventListener('visibilitychange', handleVisibilityChange)
  })
  onUnmounted(() => {
    if (autoRefreshTimer) clearInterval(autoRefreshTimer)
    document.removeEventListener('visibilitychange', handleVisibilityChange)
  })
  </script>
  
  <style scoped>
  .filter-form {
    margin-bottom: 20px;
    background: #f7f8fa;
    padding: 18px 24px 0 24px;
    border-radius: 8px;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-end;
    gap: 0 24px;
  }
  .filter-item {
    min-width: 180px;
    margin-bottom: 18px;
  }
  .el-form-item {
    margin-right: 24px;
    margin-bottom: 18px;
  }
  .exam-info {
    margin-bottom: 20px;
  }
  .action-btns-group {
    display: flex;
    flex-direction: column;
    gap: 6px; /* 行间距 */
  }
  .action-btns-row {
    display: flex;
    gap: 8px; /* 按钮间距 */
    align-items: center;
  }
  </style>
  
  <ProctorTask @refreshExamList="fetchList" /> 